package com.dyz.wsw.common.utils.security;

import java.security.*;
import java.util.Base64;

/**
 * RSA公私钥生成器
 * @author dyz
 * Time 2024/6/26 15:07
 */
public class KeyGenerator {
    /**
     * 生成公私钥对
     * @return 公私钥对
     */
    public static KeyPair generateKeyPair() {
        KeyPairGenerator keyPairGenerator = null;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 将公钥进行base64编码
     * @param publicKey 公钥
     * @return base64编码后的公钥
     */
    public static String getPublicKeyAsString(PublicKey publicKey){
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }

    /**
     * 将私钥进行Base64编码
     * @param privateKey 私钥
     * @return base64编码后的私钥
     */
    public static String getPrivateKeyAsString(PrivateKey privateKey){
        return Base64.getEncoder().encodeToString(privateKey.getEncoded());
    }
}
